package com.huawei.deveco.exportprofiler;

import com.alibaba.fastjson.JSONObject;
import com.huawei.deveco.insight.ohos.common.ProfilerException;
import com.huawei.deveco.insight.ohos.utils.JsonUtil;
import com.huawei.deveco.insight.ohos.utils.ValidateUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.ui.Messages;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.cef.browser.CefBrowser;
import org.cef.browser.CefFrame;
import org.cef.callback.CefQueryCallback;
import org.cef.handler.CefMessageRouterHandlerAdapter;

import java.io.File;
import java.io.FileWriter;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;

public class MsgRouterHandlerAdapter extends CefMessageRouterHandlerAdapter {
    private static final Logger logger = Logger.getInstance(MsgRouterHandlerAdapter.class);

    @Override
    public boolean onQuery(CefBrowser browser,
                           CefFrame frame,
                           long queryId,
                           String request,
                           boolean persistent,
                           CefQueryCallback callback) {
        JSONObject jsonObject = JsonUtil.parseObject(request, JSONObject.class);
        if (jsonObject == null) {
            return false;
        }
        var key = jsonObject.getString("key");
        var data = jsonObject.getString("data");
        if (!key.equals("exportFilterDetail")) {
            return false;
        }
        var queryRequest = JsonUtil.parseObject(data, ExportRequest.class);
        if (queryRequest == null) {
            return false;
        }
        var uuid = queryRequest.getUuid();
        try {
            ValidateUtil.validate(queryRequest);
        } catch (ProfilerException e) {
            Messages.showWarningDialog("Unexpected data type", "Warn");
            return false;
        }
        ApplicationManager.getApplication().invokeLater(() -> {
            var path = Paths.get(System.getProperty("user.home"), "Snapshot_" + UUID.randomUUID() + ".csv");
            exportToCSV(path.toFile(), queryRequest.getColumns());
            ExportAction.removeRouterByUUID(uuid);
        });
        return false;
    }

    private void exportToCSV(File file, List<ExportReqData> columns) {
        try (FileWriter writer = new FileWriter(file);
             CSVPrinter printer = new CSVPrinter(writer, CSVFormat.DEFAULT)) {
            // 写入 csv 文件首行内容
            printer.printRecord("Constructor", "Distance", "Shallow Size", "Retained Size", "Native Size", "Retained Native Size");
            for (var column : columns) {
                printer.printRecord(column.getName(),
                        column.getDistance(),
                        column.getShallowSize(),
                        column.getRetainedSize(),
                        column.getNativeSize(),
                        column.getRetainedNativeSize());
            }
            Messages.showInfoMessage("Export csv file success", "Info");
        } catch (Exception e) {
            logger.error(e.getMessage());
            Messages.showErrorDialog("Save csv failed: " + e.getMessage(), "Error");
        }
    }
}
